# Oracle连接池监控和诊断工具
# 用于实时监控Oracle连接池状态和性能

param(
    [string]$ServiceUrl = "http://localhost:5000",
    [int]$CheckInterval = 5,
    [int]$MaxChecks = 12,
    [switch]$Continuous = $false
)

Write-Host "📊 Oracle连接池监控工具" -ForegroundColor Cyan
Write-Host "========================" -ForegroundColor Cyan

# 颜色定义
$colors = @{
    Success = "Green"
    Warning = "Yellow"
    Error = "Red"
    Info = "Cyan"
}

function Write-ColoredMessage {
    param([string]$Message, [string]$Type = "Info")
    $color = $colors[$Type]
    Write-Host $Message -ForegroundColor $color
}

function Get-OraclePoolStatus {
    try {
        $url = "$ServiceUrl/api/health/oracle-pool-status"
        $response = Invoke-RestMethod -Uri $url -Method Get -TimeoutSec 10
        return $response
    } catch {
        Write-ColoredMessage "❌ 无法获取连接池状态: $($_.Exception.Message)" "Error"
        return $null
    }
}

function Test-OracleConnection {
    try {
        $url = "$ServiceUrl/api/health/oracle-test-connection"
        $response = Invoke-RestMethod -Uri $url -Method Get -TimeoutSec 15
        return $response
    } catch {
        Write-ColoredMessage "❌ 连接测试失败: $($_.Exception.Message)" "Error"
        return @{ success = $false; message = $_.Exception.Message }
    }
}

function Get-ServiceMetrics {
    try {
        $url = "$ServiceUrl/api/health"
        $response = Invoke-RestMethod -Uri $url -Method Get -TimeoutSec 5
        return $response
    } catch {
        return $null
    }
}

function Format-StatusReport {
    param($status, $connectionTest, $metrics)
    
    Write-Host "`n📋 Oracle连接池状态报告" -ForegroundColor Cyan
    Write-Host "========================" -ForegroundColor Cyan
    
    # 连接测试结果
    if ($connectionTest) {
        $connStatus = if ($connectionTest.success) { "✅ 正常" } else { "❌ 失败" }
        $connColor = if ($connectionTest.success) { "Success" } else { "Error" }
        Write-ColoredMessage "连接测试: $connStatus - $($connectionTest.message)" $connColor
    }
    
    # 连接池状态
    if ($status) {
        Write-ColoredMessage "连接池统计:" "Info"
        Write-Host "  最后耗尽时间: $($status.lastPoolExhaustionTime)" -ForegroundColor Gray
        Write-Host "  连续错误次数: $($status.consecutivePoolErrors)" -ForegroundColor Gray
        Write-Host "  当前时间: $($status.currentTime)" -ForegroundColor Gray
    }
    
    # 服务指标
    if ($metrics) {
        Write-ColoredMessage "服务健康:" "Info"
        Write-Host "  状态: $($metrics.status)" -ForegroundColor Gray
        Write-Host "  响应时间: $($metrics.totalResponseTime)ms" -ForegroundColor Gray
    }
    
    Write-Host "========================" -ForegroundColor Cyan
}

function Clear-OraclePools {
    Write-Host "🧹 清理Oracle连接池..." -ForegroundColor Yellow
    try {
        $url = "$ServiceUrl/api/health/clear-oracle-pools"
        $response = Invoke-RestMethod -Uri $url -Method Post -TimeoutSec 10
        if ($response.success) {
            Write-ColoredMessage "✅ 连接池已清理" "Success"
        } else {
            Write-ColoredMessage "❌ 清理失败: $($response.message)" "Error"
        }
    } catch {
        Write-ColoredMessage "❌ 清理请求失败: $($_.Exception.Message)" "Error"
    }
}

# 主监控循环
$checkCount = 0
$errors = 0
$successCount = 0

if ($Continuous) {
    Write-ColoredMessage "🔄 开始连续监控模式 (按Ctrl+C停止)" "Info"
    while ($true) {
        $checkCount++
        
        $status = Get-OraclePoolStatus
        $connectionTest = Test-OracleConnection
        $metrics = Get-ServiceMetrics
        
        Format-StatusReport $status $connectionTest $metrics
        
        if ($connectionTest.success) {
            $successCount++
        } else {
            $errors++
        }
        
        Write-Host "📊 统计: 检查=$checkCount, 成功=$successCount, 失败=$errors" -ForegroundColor Gray
        
        Start-Sleep -Seconds $CheckInterval
    }
} else {
    Write-ColoredMessage "📊 开始监控 (共$MaxChecks次检查)" "Info"
    
    for ($i = 1; $i -le $MaxChecks; $i++) {
        Write-Host "`n🔍 检查 #$i" -ForegroundColor Yellow
        
        $status = Get-OraclePoolStatus
        $connectionTest = Test-OracleConnection
        $metrics = Get-ServiceMetrics
        
        Format-StatusReport $status $connectionTest $metrics
        
        if ($connectionTest.success) {
            $successCount++
        } else {
            $errors++
        }
        
        if ($i -lt $MaxChecks) {
            Write-Host "⏳ 等待$CheckInterval秒后进行下一次检查..." -ForegroundColor Gray
            Start-Sleep -Seconds $CheckInterval
        }
    }
    
    Write-Host "`n📈 监控完成" -ForegroundColor Green
    Write-Host "总检查次数: $MaxChecks" -ForegroundColor Green
    Write-Host "成功连接: $successCount" -ForegroundColor Green
    Write-Host "失败连接: $errors" -ForegroundColor $(if ($errors -gt 0) { "Red" } else { "Green" })
    Write-Host "成功率: $([math]::Round(($successCount/$MaxChecks)*100, 2))%" -ForegroundColor Green
}

# 菜单选项
function Show-Menu {
    Write-Host "`n🎯 可用操作:" -ForegroundColor Cyan
    Write-Host "1. 清理连接池" -ForegroundColor Yellow
    Write-Host "2. 重新测试连接" -ForegroundColor Yellow
    Write-Host "3. 退出" -ForegroundColor Yellow
    
    $choice = Read-Host "请选择操作 (1-3)"
    switch ($choice) {
        "1" { Clear-OraclePools }
        "2" { 
            $test = Test-OracleConnection
            Write-ColoredMessage "连接测试结果: $($test.message)" $(if ($test.success) { "Success" } else { "Error" })
        }
        "3" { exit }
        default { Write-ColoredMessage "无效选择" "Error" }
    }
}

# 如果非连续模式，显示菜单
if (-not $Continuous) {
    Show-Menu
}